<template>
	<div class="search-page">
	<van-nav-bar
	 
	  left-arrow
	  @click-left="$router.back()">
	  
	  <template #title>
		  <van-search
		    v-model="key_word"
		    show-action
		    placeholder="请输入搜索关键词"
		    @search="onSearch"
			@input = "input"
		  >
		    <template #action>
		      <div @click="onSearch(key_word)">搜索</div>
		    </template>
		  </van-search>
	  </template>
	  </van-nav-bar>
	  
	  
	  <div class="resultList" v-show="resultList.length>0">
		  
		 <van-cell v-for="item in resultList" @click="onSearch(item.title)">
			 {{item.title}}
		 </van-cell> 
		  
	  </div>
	  <div v-show="resultList.length===0">
		  <van-cell v-for="item in search_history" @click="onSearch(item.value)">
		  			 {{item.value}}
		  </van-cell> 
		  
		   <div @click="clear" v-if="search_history.length>0">清除</div>
		 
	  </div>
	  
	  
	  
	  

	  
	</div>
</template>

<script>
	import { Search } from 'vant';
	import { searchApi } from '@/api/search';
	
	let timer = null;//  
	
	export default {
		name:'SearchView',
		components:{
			[Search.name]:Search
		},
		data(){
			return {
				key_word:'',
				resultList:[],
				search_history:[]
			}
		},
		created() {
			    let search_history = localStorage.getItem('search_history');
				if(search_history){
					this.search_history = JSON.parse(search_history)
				}
			  
		},
		beforeDestroy() {
			 clearTimeout(timer);
			 timer = null
		},
		methods:{
			clear(){
				 localStorage.removeItem('search_history')
				 this.search_history = []
			},
			onSearch(key_word){
				
				let index = this.search_history.findIndex(V=>V.value===key_word )
				if(index>=0){
					 this.search_history.splice(index,1)
				}
				
				this.search_history.unshift({
					value:key_word,
					timestamp:+new Date()
				});
				
				localStorage.setItem('search_history',JSON.stringify(this.search_history))
				
				
				this.$router.push('/searchList?key_word='+key_word)
				
			},
			input(key_word){
		
				key_word = key_word.trim();
				if(key_word.length === 0){
					this.resultList = [];
					return 
				}
				
				if(timer){
					clearTimeout(timer)
				}
				
				timer = setTimeout(v=>{
					searchApi({
						key_word
					}).then(res=>{
						console.log(res)
						
						this.resultList = res.data
					});
					   
					   
				},500)
				
				

				  
			}
		}
	}
</script>

<!-- <style module>
	
	.red{
		color: red;
	}
</style> -->

<style lang="scss" scoped>
.search-page{
	background-color: #eee;
	min-height: 100vh;
}
	.search-page ::v-deep .van-nav-bar__title{
		
		max-width: 100%;
		width: calc(100% - 50px);
	}
	
	.resultList{
		width: 100%;
		position: fixed;
		top: 50px;
		left: 0;
		background-color: #fff;
	}
	

</style>